﻿Imports System
Imports System.Globalization
Imports System.Xml
Imports System.Data
Imports System.Collections
Imports System.Data.SqlClient
Imports System.Web
Imports System.Text.RegularExpressions
Imports System.Net.Mail
Imports System.Web.UI

Public Class clsLibreria
    Dim Param As Parametros = New Parametros

#Region "Validaciones"
    ''' <summary>
    ''' VALIDA EL RUT ENTREGADO ACEPTA FORMATO CON PUNTOS Y GUION
    ''' </summary>
    ''' <param name="Rut">Rut a validar, todos los formatos</param>
    ''' <returns>Verdadero o Falso</returns>
    ''' <remarks></remarks>
    Public Function ValidarRut(ByVal Rut As String) As Boolean
        Dim i As Integer
        Dim RutEntero As String
        Dim RutDiv As String
        Dim StrMult As String
        Dim LargoRut As String
        Dim LargoMult As String
        Dim Suma As Integer
        Dim Rut_i As String
        Dim Factor_i As String
        Dim Resto As Integer
        Dim Digito As String

        Rut = Rut.Trim()
        If Rut = "" Then
            ValidarRut = False
            Exit Function
        End If

        Rut = Rut.Replace("-", "")
        Rut = Rut.Replace(".", "")
        RutEntero = Rut.Substring(0, Rut.Length - 1)

        If Rut = "0" Or Rut = "" Then
            ValidarRut = False
            Exit Function
        End If

        If IsNumeric(RutEntero) Then
            If CDbl(RutEntero) = 0 Then
                ValidarRut = False
                Exit Function
            End If
        Else
            ValidarRut = False
            Exit Function
        End If

        RutDiv = Rut.Substring(Rut.Length - 1, 1)
        StrMult = "765432765432"
        LargoRut = RutEntero.Length
        LargoMult = StrMult.Length

        Suma = 0
        For i = 1 To LargoRut
            Rut_i = RutEntero.Substring(LargoRut - i, 1)
            Factor_i = StrMult.Substring(LargoMult - i, 1)
            Suma = Suma + CInt(Rut_i) * CInt(Factor_i)
        Next

        Resto = 11 - (Suma Mod 11)

        Select Case Resto
            Case 11
                Digito = "0"
            Case 10
                Digito = "K"
            Case Else
                Digito = CStr(Resto)
        End Select

        ValidarRut = (RutDiv.ToUpper() = Digito)

    End Function

    ''' <summary>
    ''' CALCULA EL DIGITO VERIFICADOR DE UN RUT ENTREGADO
    ''' </summary>
    ''' <param name="Rut">RUT SIN DIGITO VERIFICADOR</param>
    ''' <returns>DIGITO VERIFICADOR DEL RUT, VACIO SI NO ES NUMERICO EL ENTREGADO</returns>
    ''' <remarks></remarks>
    Public Function CalculaDVRUT(ByVal Rut As String) As String
        Dim i As Integer
        Dim RutEntero As String
        Dim StrMult As String
        Dim LargoRut As String
        Dim LargoMult As String
        Dim Suma As Integer
        Dim Rut_i As String
        Dim Factor_i As String
        Dim Resto As Integer
        Dim Digito As String

        Rut = Rut.Trim()
        Rut = Rut.Replace("-", "")
        Rut = Rut.Replace(".", "")
        RutEntero = Rut

        If Rut = "0" Or Rut = "" Then
            CalculaDVRUT = ""
            Exit Function
        End If

        If IsNumeric(RutEntero) Then
            If CDbl(RutEntero) = 0 Then
                CalculaDVRUT = ""
                Exit Function
            End If
        Else
            CalculaDVRUT = ""
            Exit Function
        End If

        StrMult = "765432765432"
        LargoRut = RutEntero.Length
        LargoMult = StrMult.Length

        Suma = 0
        For i = 1 To LargoRut
            Rut_i = RutEntero.Substring(LargoRut - i, 1)
            Factor_i = StrMult.Substring(LargoMult - i, 1)
            Suma = Suma + CInt(Rut_i) * CInt(Factor_i)
        Next

        Resto = 11 - (Suma Mod 11)

        Select Case Resto
            Case 11
                Digito = "0"
            Case 10
                Digito = "K"
            Case Else
                Digito = CStr(Resto)
        End Select

        CalculaDVRUT = Digito

    End Function

    ''' <summary>
    ''' FUNCION PARA VALIDAR FECHA
    ''' </summary>
    ''' <param name="Fecha">String con fecha</param>
    ''' <returns>Verdadero o Falso según corresponda</returns>
    ''' <remarks></remarks>
    Public Function ValidarFecha(ByVal Fecha As String) As Boolean
        Dim Day As Integer
        Dim Month As Integer
        Dim Year As Integer
        Dim FechaFinal As Date

        If Fecha.Length <> 10 Then
            ValidarFecha = False
            Exit Function
        End If

        Try
            Day = CInt(Fecha.Substring(0, 2))
        Catch
            ValidarFecha = False
            Exit Function
        End Try

        Try
            Month = CInt(Fecha.Substring(3, 2))
        Catch
            ValidarFecha = False
            Exit Function
        End Try

        Try
            Year = CInt(Fecha.Substring(6, 4))
        Catch
            ValidarFecha = False
            Exit Function
        End Try

        Try
            FechaFinal = CDate(Fecha)
        Catch
            ValidarFecha = False
            Exit Function
        End Try

        ValidarFecha = True
    End Function
#End Region

#Region "Constructor/Destructor"
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub

    Public Sub Dispose()
        Try
            GC.SuppressFinalize(Me)
        Catch ex As Exception
        End Try
    End Sub

    Public Sub New()
        MyBase.New()
    End Sub
#End Region

#Region "Formatos y Desformatos"
    Public Function FormatearMonedaXML(ByRef objXML As XmlDataDocument, ByVal NomParametro As String, Optional ByVal NomParametroMoneda As String = "PESOS", Optional ByVal Simbolo As Boolean = True) As Integer
        Dim objNode As XmlNode
        Dim pNode As XmlNode
        Dim strMoneda As String = NomParametroMoneda
        Dim cant As Integer = 0
        Try
            objXML.DataSet.EnforceConstraints = False
            For Each objNode In objXML.SelectNodes("//" & NomParametro)
                pNode = objNode.ParentNode
                Try
                    strMoneda = pNode.Item(NomParametroMoneda).InnerText()
                Catch ex As Exception
                    strMoneda = IIf(NomParametroMoneda = "nom_moneda", "PESOS", NomParametroMoneda)
                End Try
                objNode.InnerText = FormatearMoneda(objNode.InnerText, strMoneda, Simbolo)
            Next
            Return cant
        Catch objException As Exception
            Return -1
        End Try
    End Function

    Private Function FormatearMoneda(ByVal value As Object, ByVal formato As String, Optional ByVal Simbolo As Boolean = True, Optional ByVal CultuIdioma As String = "es-CL") As String
        Dim formatodecimal As String = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
        Dim CultureMonto As Decimal
        If IsNothing(value) Or value Is System.DBNull.Value Then
            Return "0"
        End If
        If value.ToString() = "" Or value.ToString() = "0" Then
            Return "0"
        End If
        Dim strMonto As String ' = value.ToString
        If formatodecimal = "'" Then
            CultureMonto = Convert.ToDecimal(value.ToString.Replace(",", "."))
        Else
            CultureMonto = Convert.ToDecimal(value.ToString.Replace(".", ","))
        End If
        Dim nfi As NumberFormatInfo = New CultureInfo(CultuIdioma, False).NumberFormat
        Select Case formato
            Case "PESOS"
                If Simbolo Then
                    strMonto = CultureMonto.ToString("$ #,##0;$-#,##0;Zero", nfi)
                Else
                    strMonto = CultureMonto.ToString("#,##0;-#,##0;Zero", nfi)
                End If
            Case "UF"
                If Simbolo Then
                    strMonto = CultureMonto.ToString("UF #,##0.0000;UF-#,##0.0000;Zero", nfi)
                Else
                    strMonto = CultureMonto.ToString("#,##0.0000; -#,##0.0000;Zero", nfi)
                End If
            Case Else
                If Simbolo Then
                    strMonto = CultureMonto.ToString("US$ #,##0.00;US$-#,##0.00;Zero", nfi)
                Else
                    strMonto = CultureMonto.ToString("#,##0.00; -#,##0.00;Zero", nfi)
                End If
        End Select
        Return strMonto
    End Function

    Public Function FormatearRut(ByVal sRut As String)
        Dim Rut As String
        Dim Invertido As String
        Dim i As Integer
        Dim dtexto As String
        Dim cnt As Integer
        FormatearRut = ""
        Rut = sRut.Replace(" ", "")
        Invertido = ""
        Rut = DesFormatearRut(Rut)
        i = Rut.Length
        Do While i >= 1
            Invertido = Invertido & Rut.Substring(i - 1, 1)
            i = i - 1
        Loop

        dtexto = Invertido.Substring(1 - 1, 1) & "-"
        cnt = 0
        i = 2
        Do While i <= Rut.Length
            If cnt = 3 Then
                dtexto = dtexto & "."
                cnt = 1
            Else
                cnt = cnt + 1
            End If
            dtexto = dtexto & Invertido.Substring(i - 1, 1)
            i = i + 1
        Loop

        i = dtexto.Length
        Do While i >= 1
            FormatearRut = FormatearRut & dtexto.Substring(i - 1, 1)
            i = i - 1
        Loop
    End Function

    Public Function DesFormatearRut(ByVal sRut As String) As String
        Dim Rut As String
        Rut = sRut.Replace(" ", "")
        Rut = Rut.Replace(".", "")
        Rut = Rut.Replace("-", "")
        DesFormatearRut = Rut
    End Function

    Public Function FormatearMonto(ByVal Monto As String, Optional ByVal FormatoPara As String = "ANTIGUO", Optional ByVal CultuIdioma As String = "es-CL") As String
        Dim NumMonto As Double
        Dim MontoDif As Double
        Dim Elmonto As Long
        Dim CultureMonto As Decimal

        Try
            Select Case FormatoPara
                Case "ANTIGUO"
                    If Monto <> "0" Then
                        Elmonto = Math.Round(Val(Monto), 0)
                        MontoDif = Elmonto - Val(Monto)

                        If MontoDif = 0 Then
                            Monto = Math.Round(Val(Monto), 0)
                        End If

                        NumMonto = Val(Monto)
                        Monto = String.Format("{0:#,###}", NumMonto)
                        Monto = Monto.Replace(",", ".")

                    End If

                Case "EXCEL"
                    Dim formatodecimal = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
                    Monto = Monto.Replace(".", formatodecimal)
                Case "XSL"
                    Dim formatodecimal = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
                    Monto = Monto.Replace(".", formatodecimal)
                    Dim nfi As NumberFormatInfo = New CultureInfo(CultuIdioma, False).NumberFormat
                    CultureMonto = CDec(Monto)
                    Monto = CultureMonto.ToString("N", nfi)
                Case "HTML"
                    Dim formatodecimal = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
                    Monto = Monto.Replace(".", formatodecimal)
                    Dim nfi As NumberFormatInfo = New CultureInfo(CultuIdioma, False).NumberFormat
                    CultureMonto = CDec(Monto)
                    Monto = CultureMonto.ToString("N", nfi)
                Case "MONEDA" ' Solo para grillas que se llenen con DataSet
                    Dim nfi As NumberFormatInfo = New CultureInfo(CultuIdioma, False).NumberFormat
                    CultureMonto = CDec(Monto)
                    Monto = "$ " & CultureMonto.ToString("N", nfi)
                Case "MONTO"
                    Monto = FormatNumber(Monto, 0).ToString
                Case "MONTOMONEDA"
                    Monto = "$ " & FormatNumber(Monto, 0).ToString
                Case "GRILLA"
            End Select
            FormatearMonto = Monto
        Catch
            FormatearMonto = Monto
        End Try
    End Function

    Public Function FormatearMontoXML(ByRef objXML As XmlDataDocument, ByVal NomParametro As String, Optional ByVal FormatoPara As String = "ANTIGUO") As String
        Dim objNode As XmlNode
        Try
            objXML.DataSet.EnforceConstraints = False
            For Each objNode In objXML.SelectNodes("//" & NomParametro)
                objNode.InnerText = FormatearMonto(objNode.InnerText, FormatoPara)
            Next
            Return "0"
        Catch objException As Exception
            Return "-1"
        End Try
    End Function

    Public Function FormatearFechaXML(ByRef objXML As XmlDataDocument, ByVal NomParametro As String, Optional ByVal FormatoPara As String = "DD/MM/YYYY") As String
        Dim objNode As XmlNode
        Try
            objXML.DataSet.EnforceConstraints = False
            For Each objNode In objXML.SelectNodes("//" & NomParametro)
                objNode.InnerText = objNode.InnerText.Trim().Substring(0, 10).Replace(Convert.ToChar("-"), Convert.ToChar("/"))
            Next
            Return "0"
        Catch objException As Exception
            Return "-1"
        End Try
    End Function

    Public Function FormatearRUTXML(ByRef objXML As XmlDataDocument, ByVal NomParametro As String) As String
        Dim objNode As XmlNode
        Try
            objXML.DataSet.EnforceConstraints = False
            For Each objNode In objXML.SelectNodes("//" & NomParametro)
                objNode.InnerText = FormatearRut(objNode.InnerText)
            Next
            Return "0"
        Catch objException As Exception
            Return "-1"
        End Try
    End Function
#End Region

#Region "Varias de uso Interno y Externo"
    Public Function RevisaErrores( _
               ByVal DsError As DataSet, _
               ByRef GlsError As String, _
               ByRef SrcError As String, _
               ByRef WsError As String, _
               ByRef MetError As String, _
               ByRef NumError As String) As String

        ' Versión COMPATIBLE LibPagosTramasPlus / Resto del Portal...
        Dim CodError As String
        Dim table As System.Data.DataTable
        Dim tablename As String
        Dim i As Integer
        Dim n As Long
        GlsError = ""
        SrcError = ""
        WsError = ""
        MetError = ""
        NumError = ""

        If DsError Is Nothing Then Return "0"

        With DsError
            For i = 0 To .Tables.Count() - 1
                table = .Tables(i)
                tablename = LCase(table.TableName)
                n = table.Rows.Count
                If n = 0 Then GoTo Siguiente_Tabla
                With table.Rows(0)
                    Try
                        CodError = .Item("ErrorNumber")
                        GoTo HayErrores
                    Catch objException As Exception
                    End Try
                End With

Siguiente_Tabla:
            Next i
            Return "0"
HayErrores:
            With table.Rows(0)
                Try
                    CodError = .Item("ErrorNumber")
                Catch objException As Exception
                End Try
                Try
                    GlsError = .Item("ErrorMessage")
                Catch objException As Exception
                End Try
                Try
                    SrcError = .Item("ErrorSeverity")
                Catch objException As Exception
                End Try
                Try
                    WsError = .Item("ErrorState")
                Catch objException As Exception
                End Try
                Try
                    MetError = .Item("ErrorProcedure")
                Catch objException As Exception
                End Try
                Try
                    NumError = .Item("ErrorNumber")
                Catch objException As Exception
                End Try
                Return CodError
            End With
        End With
    End Function

    Public Function ObtRutParteNum(ByVal rut As String) As String
        rut = rut.Replace(".", "")
        rut = rut.Replace("-", "")
        ObtRutParteNum = rut.Substring(0, rut.Length - 1)
    End Function

    Public Function ObtRutParteDV(ByVal rut As String) As String
        rut = rut.Replace(".", "")
        rut = rut.Replace("-", "")
        ObtRutParteDV = rut.Substring(rut.Length - 1, 1)
    End Function

    Public Function SetearFoco(ByVal pagina As Page, ByVal NombreCodigo As String, ByVal Campo As String)
        pagina.RegisterStartupScript(NombreCodigo, "<script language=javascript> document.forms[0]['" & Campo & "'].focus(); </script>")
    End Function

    Public Function RandomPassword()
        Dim RandomPasswd As String
        Dim RandomDigits As Integer

        Randomize()

        RandomPasswd = ""
        RandomDigits = Int((122 - 97 + 1) * Rnd() + 97)
        RandomPasswd = RandomPasswd & Chr(RandomDigits)
        RandomDigits = Int((122 - 97 + 1) * Rnd() + 97)
        RandomPasswd = RandomPasswd & Chr(RandomDigits)
        RandomDigits = Int((122 - 97 + 1) * Rnd() + 97)
        RandomPasswd = RandomPasswd & UCase(Chr(RandomDigits))
        RandomDigits = Int((122 - 97 + 1) * Rnd() + 97)
        RandomPasswd = RandomPasswd & Chr(RandomDigits)
        RandomDigits = Int((9999 - 1000 + 1) * Rnd() + 1000)
        RandomPasswd = RandomPasswd & RandomDigits

        Return RandomPasswd
    End Function

    Function HashPassword(ByVal TextToHash As String) As String
        Dim password As String
        Dim x As System.Security.Cryptography.MD5CryptoServiceProvider = New System.Security.Cryptography.MD5CryptoServiceProvider
        Dim bs As Byte() = System.Text.Encoding.UTF8.GetBytes(TextToHash)
        bs = x.ComputeHash(bs)
        Dim s As System.Text.StringBuilder = New System.Text.StringBuilder
        For Each b As Byte In bs
            s.Append(b.ToString("x2").ToLower)
        Next
        password = s.ToString
        Return password
    End Function

    Public Function TransXML(ByVal strXML As String) As DataSet
        Dim ods As New DataSet

        strXML = strXML.Replace("&", "&amp;")
        ods.ReadXml(New IO.StringReader(strXML))

        Return ods
    End Function

    Public Function Transformar(ByVal xslPath As String, ByVal strXML As String) As String
        Dim xsl As New System.Xml.Xsl.XslCompiledTransform()
        xsl.Load(xslPath)
        Dim msIn As New System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(strXML))
        Dim msOut As New System.IO.MemoryStream()
        msIn.Position = 0
        Dim trInput As New System.Xml.XmlTextReader(msIn)
        Dim twOutput As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(msOut, xsl.OutputSettings)
        xsl.Transform(trInput, twOutput)
        trInput.Close()
        msIn.Close()
        msOut.Position = 0
        Dim sr As New System.IO.StreamReader(msOut)
        Dim xmlStr As String = [String].Format("{0}", sr.ReadToEnd())
        msOut.Close()
        sr.Close()
        Return xmlStr
    End Function
#End Region

End Class
